package com.jn.erp.web.api.student.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.common.annotation.Log;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.enums.BusinessType;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.utils.DateUtils;
import com.jn.erp.web.api.course.entity.TCourse;
import com.jn.erp.web.api.course.entity.TCoursePrice;
import com.jn.erp.web.api.course.service.TCoursePriceService;
import com.jn.erp.web.api.course.service.TCourseService;
import com.jn.erp.web.api.course.task.TCourseOrderTask;
import com.jn.erp.web.api.institution.entity.vo.EmployeeVo;
import com.jn.erp.web.api.institution.service.EmployeeService;
import com.jn.erp.web.api.student.entity.*;
import com.jn.erp.web.api.student.entity.dto.EnrollmentStuDto;
import com.jn.erp.web.api.student.entity.dto.StudentBaseInfoDTO;
import com.jn.erp.web.api.student.entity.dto.StudentClueDto;
import com.jn.erp.web.api.student.entity.dto.StudentClueExportDto;
import com.jn.erp.web.api.student.entity.vo.StudentCourseVo;
import com.jn.erp.web.api.student.service.*;
import com.jn.erp.web.api.student.utils.ImportExportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student")
@Api(value = "学生管理", tags = "学生管理")
public class StudentController extends BaseWebAuthController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private ImportExportService importExportService;

    @Autowired
    private com.jn.erp.web.api.student.service.ClassService classService;

    @Autowired
    private ClassGradeService classGradeService;

    @Autowired
    private StudentCourseService studentCourseService;

    @Autowired
    StudentContactsUserService studentContactsUserService;

    @Autowired
    private RenewalAlertsConfigService renewalAlertsConfigService;


    @Autowired
    private StudentContactRecordService studentContactRecordService;

    @Autowired
    private StudentClassService studentClassService;

    @Autowired
    private StudentUserService studentUserService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TCourseService tCourseService;

    @Autowired
    private TCoursePriceService tCoursePriceService;

    @Autowired
    private TCourseOrderTask tCourseOrderTask;

    @Autowired
    private StudentClassRelaService studentClassRelaService;


    //导入 , 时间格式

    // 在读学员2 历史5 线索1
    @ApiOperation("学员列表")
    @GetMapping("/list")
    public TableDataInfo studentList(Student student) {
        // 机构id报读
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        // 前端传 2-- 在读学员  5 -- 历史学员
        startPage();
        student.setDeleted(0);
        List<Student> list = studentService.getList(student);
        TableDataInfo dataTable = getDataTable(list);
        // 没有跟进人 线索学员 1
        return dataTable;
    }

    /**
     * 学员详情回显接口
     */
    @PostMapping("/getStudent")
    public AjaxResult getStudent(@RequestBody Student student) {
        // 机构id报读
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        Student stu = studentService.getStudent(student);
        return success(stu);
    }


    /**
     * 编辑新增学员基本信息
     *
     * @param studentDTO
     * @return
     */
    @Log(title = "编辑新增学员基本信息", businessType = BusinessType.UPDATE)
    @PostMapping("/save")
    public AjaxResult saveStudent(@RequestBody StudentBaseInfoDTO studentDTO) {
        //        获取登录者信息
        studentDTO.setOrgId(Long.parseLong(loginDeptAuth()));
        Long stu = studentService.studentUnifysaveOrUpdateByDTO(studentDTO);
        return AjaxResult.success(stu);

    }

    /**
     * 学员报名
     */
// tCourse/list
    @Log(title = "学员报名")
    @PostMapping("/application")
    public AjaxResult saveCourse(@RequestBody StudentCourseVo studentCourseVo) {
        List<StudentCourse> sc = studentCourseService.addOne(studentCourseVo);
        return success(sc);
    }

    /**
     * 模糊查询报名上课学员
     *
     * @param student
     * @return
     */
    @PostMapping("/allStudent")
    public AjaxResult allStudent(@RequestBody Student student) {
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        List<Student> stu = studentService.allStudent(student);
        return success(stu);
    }

    /**
     * 全部学员
     *
     * @param student
     * @return
     */
    @PostMapping("/allStudentList")
    public AjaxResult allStudentList(@RequestBody Student student) {
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        List<Student> stu = studentService.studentList(student);
        return success(stu);
    }

    /**
     * 删除跟进记录
     *
     * @param
     * @return
     */
    @PostMapping("/applicationDelete")
    public AjaxResult applicationDelete(@RequestBody StudentCourse studentCourse) {
        long id = studentCourse.getId();
        StudentCourse byId = studentCourseService.getById(id);
        byId.setDeleted(1);
        studentCourseService.updateById(byId);
        return AjaxResult.success("删除成功");
    }


    /**
     * 报名回显接口
     * 前端传学生id
     *
     * @param
     * @return
     */
    @PostMapping("/applicationOne")
    public AjaxResult applicationOne(@RequestBody Student student) {
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        Student stu = studentService.applicationOne(student);
        if (stu == null) {
            return success("暂无数据");
        }
        return AjaxResult.success(stu);
    }


    // 历史学员转换成在读学员
    @PostMapping("/changeLearning")
    public AjaxResult changeLearning(@RequestBody Student student) {
        //2 是 在学学员
        if (studentService.changeStage(student.getId(), 2, true)) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.error("操作失败");
        }
    }

    // 转为 历史的
    @Log(title = "报读学员转历史学员", businessType = BusinessType.CLEAN)
    @PostMapping("/changeGraduation")
    public AjaxResult changeGraduation(@RequestBody Student student) {
        String s = studentService.changeStageHisyory(student);
        return AjaxResult.success(s);

    }


    @ApiOperation("变为线索学员")
    @PostMapping("/changeIntention")
    public AjaxResult changeIntention(@RequestBody Student student) {
        if (studentService.changeStage(student.getId(), 1, true)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 列表模糊查询下拉列表
     * 学生来源
     */
    @PostMapping("/resource")
    public AjaxResult resource() {
        List<Student> list = studentService.list();
        ArrayList<Object> list1 = new ArrayList<>();
        for (Student student : list) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("label", student.getJoinWay());
            map.put("value", student.getId());
            list1.add(map);
        }
        return success(list1);
    }


    /**
     * 班级名称
     *
     * @return
     */
    @PostMapping("/classList")
    public AjaxResult classList(@RequestBody StudentClass tClass) {
        tClass.setOrgId(Long.parseLong(loginDeptAuth()));
        LambdaQueryWrapper<StudentClass> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentClass::getOrgId, tClass.getOrgId());
        List<StudentClass> list = classService.list(wrapper);
        ArrayList<Object> list1 = new ArrayList<>();
        for (StudentClass classes : list) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("value", classes.getId());
            map.put("label", classes.getName());
            list1.add(map);
        }
        return success(list1);
    }

    /**
     * 年级列表
     *
     * @return
     */
    @PostMapping("/gradeList")
    public AjaxResult gradeList() {
        List<StudentClassGrade> list = classGradeService.list();
        ArrayList<Object> list1 = new ArrayList<>();
        for (StudentClassGrade classGrade : list) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("value", classGrade.getId());
            map.put("label", classGrade.getName());
            list1.add(map);
        }
        return success(list1);
    }

    /**
     * 班级课程关联列表
     */
    @PostMapping("/classCourseList")
    public AjaxResult classCourseList(@RequestBody StudentClass tClass) {
        tClass.setOrgId(Long.parseLong(loginDeptAuth()));
        StudentClass list = studentClassService.classCourseList(tClass);
        return AjaxResult.success(list);
    }


    /**
     * 删除线索学员  彻底删除 还原
     */

    @ApiOperation("删除线索学员")
    @PostMapping("/deleteClue")
    public AjaxResult delete(@RequestBody Student student) {
        studentService.deleteClue(student);
        return success("操作成功");
    }


    // 分配跟进人，学管师
    @PostMapping("/getCounselor")
    public AjaxResult getCounselor(@RequestBody Student student) {
        student.setCreator(getUserId());
        studentService.getCounselor(student);
        return AjaxResult.success("分配成功");
    }

    /**
     * 报读情况列表
     *
     * @return
     */
    @GetMapping("/enrollmentStatus")
    public TableDataInfo enrollmentStatus(EnrollmentStuDto student) {
        long orgId = Long.parseLong(loginDeptAuth());
        //        1, 意向学员 2, 在学学员 3 结业学员 4.报读学员 5.历史学员
        startPage();
        student.setOrgId(orgId);
        List<EnrollmentStuDto> list = studentService.enrollmentList(student);
        return getDataTable(list);
    }


    // 统计剩余课时，剩余金额
    @PostMapping("/remainderCount")
    public AjaxResult remainderCount(@RequestBody EnrollmentStuDto student) {
        long orgId = Long.parseLong(loginDeptAuth());
        student.setOrgId(orgId);
        EnrollmentStuDto remainderCount = studentService.remainderCount(student);
        return AjaxResult.success(remainderCount);
    }


    /**
     * 跟进管理 添加和修改跟进记录
     *
     * @param
     * @param
     * @return
     */
    @Log(title = "跟进管理 添加和修改跟进记录", businessType = BusinessType.UPDATE)
    @PostMapping("/followSave")
    public AjaxResult followSave(@RequestBody StudentContactRecord studentContactRecord) {
        studentContactRecord.setOrgId(Long.parseLong(loginDeptAuth()));
        studentContactRecord.setCounselorId(String.valueOf(getUserId()));
        if (studentContactRecordService.saveOrUpdateByRecord(studentContactRecord)) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.error("操作失败");
        }
    }

    /**
     * 删除跟进记录
     *
     * @param studentContactRecord
     * @return
     */
    @Log(title = "删除跟进人员", businessType = BusinessType.DELETE)
    @PostMapping("/followDelete")
    @Transactional
    public AjaxResult followDelete(@RequestBody StudentContactRecord studentContactRecord) {
        long id = studentContactRecord.getId();
        StudentContactRecord byId = studentContactRecordService.getById(id);
        long studentId = byId.getStudentId();
        Student student = studentService.getById(studentId);
        student.setDeleted(1);
        studentService.updateById(student);
        UpdateWrapper<StudentContactRecord> up = new UpdateWrapper();
        up.set("deleted", 1);
        up.eq("student_id", studentId);
        studentContactRecordService.update(up);
        return AjaxResult.success("删除成功");
    }


    /**
     * 删除跟进记录
     *
     * @param studentContactRecord
     * @return
     */
    @Log(title = "删除跟进记录", businessType = BusinessType.DELETE)
    @PostMapping("/followDeleteRecord")
    @Transactional
    public AjaxResult followDeleteRecord(@RequestBody StudentContactRecord studentContactRecord) {
        long id = studentContactRecord.getId();
        StudentContactRecord byId = studentContactRecordService.getById(id);
        long studentId = byId.getStudentId();
        // 查询有几条跟进记录
        QueryWrapper<StudentContactRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        wrapper.eq("student_id", studentId);
        wrapper.eq("org_id", Long.parseLong(loginDeptAuth()));
        List<StudentContactRecord> list = studentContactRecordService.list(wrapper);
        if (list.size() > 1) {
            byId.setDeleted(1);
            studentContactRecordService.updateById(byId);
        } else {
            return AjaxResult.error("不能删除最后一条跟进记录");
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 一个人的跟进列表 有stuentId
     *
     * @param studentContactRecord
     * @return
     */
    @PostMapping("/followListById")
    public AjaxResult followListById(@RequestBody StudentContactRecord studentContactRecord) {
        studentContactRecord.setOrgId(Long.parseLong(loginDeptAuth()));
        List<StudentContactRecord> list = studentContactRecordService.followListById(studentContactRecord);
        return AjaxResult.success(list);
    }

    /**
     * 跟进管理大列表
     *
     * @param studentContactRecord
     * @return
     */
    @GetMapping("/followList")
    public TableDataInfo followList(StudentContactRecord studentContactRecord) {
        // 机构id
        studentContactRecord.setOrgId(Long.parseLong(loginDeptAuth()));
        startPage();
        List<StudentContactRecord> records = studentContactRecordService.followList(studentContactRecord);
        return getDataTable(records);
    }
//
//    /**
//     * 线索管理的跟进
//     */
//    @PostMapping("/cluefollow")
//    public AjaxResult followList(@RequestBody Student student) {
//        Student stu =  studentService.followList(student);
//        return success(stu);
//    }


    /**
     * 导出报读信息模板
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation("导出模板")
    @GetMapping("/exportInfo")
    public void enrollTemplate(HttpServletResponse response, @RequestParam(value = "stage") Integer
            stage) {
//        报读学员信息导入
        if (stage == 4) {
            try {
                importExportService.exportTemplate(response, Long.parseLong(loginDeptAuth()));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

//            importExportService.exportExcel(response, enrollexcelHeaderMap(), null, "学员报读导入模板");
        }
        // 在读学员基本信息
        if (stage == 2) {
            importExportService.exportExcel(response, excelHeaderMap(), null, "学员基本信息导入模板");
        }
        if (stage == 1) {
            try {
                importExportService.exportClueTemplate(response, Long.parseLong(loginDeptAuth()));
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    private Map<String, String> enrollexcelHeaderMap() {
        return new LinkedHashMap<String, String>() {{
            put("name", "姓名");
            put("mobile", "手机号");
            put("genderName", "性别");
            put("courseName", "课程名称");
            put("className", "班级名称");
            put("countLessonTotal", "购买课时");
            put("freeClassHours", "赠送数量");
            put("countLessonComplete", "已上课时");
            put("amount", "应收金额");
            put("paidAmount", "实付金额");
            put("expireDate", "课程到期日期");

//            put("countLessonRefund", "退转数量");
//            put("remainderLesson", "剩余课时");
//            put("spendAmount", "课消金额");
//            put("remainderAmount", "剩余课消金额");
//            put("unitPrice", "单价");
//            put("courseAmount", "总价");

            put("remark", "备注");
        }};
    }

    // 在读学员导入方法
    private Map<String, String> excelHeaderMap() {
        return new LinkedHashMap<String, String>() {{
            put("name", "姓名");
            put("mobile", "手机号");
            put("genderName", "性别");
            put("age", "年龄");
            put("birthday", "出生日期");
            put("attendSchool", "就读学校");
            put("counselorName", "跟进人");
            put("management", "学管师");
            put("gradeName", "当前年级");
            put("joinWay", "学生来源");
            //            put("creatName", "创建人");
            put("remark", "备注");
        }};
    }

    private Map<String, String> excelHeaderMapClue() {
        return new LinkedHashMap<String, String>() {{
            put("name", "姓名");
            put("mobile", "手机号");
            put("genderName", "性别");
            put("age", "年龄");
            put("birthday", "出生日期");
            put("attendSchool", "就读学校");
            put("gradeName", "当前年级");
            put("joinWay", "来源");
//            put("creatName", "创建人");
            put("remark", "备注");
        }};
    }




    /**
     * Object转BigDecimal类型
     *
     * @param value 要转的object类型
     * @return 转成的BigDecimal类型数据
     */
    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }


    /**
     * 导入数据
     */
    @PostMapping("import")
    @ApiOperation(value = "导入数据")
    public AjaxResult importData(@RequestBody MultipartFile file, Integer stage) {

        //导入
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(0);
        try {
            // 解析excel获取对应list
            List<StudentClueDto> easyPoisList = ExcelImportUtil.importExcel(file.getInputStream(), StudentClueDto.class, params);
            List<Student> list = new ArrayList<>();
            // 来源
            List<Student> listSource = studentService.listSource();
            Map<String, String> sourceMap = listSource.stream().collect(Collectors.toMap(Student::getDictLabel, Student::getDictValue));
            // 创建人
            EmployeeVo employeeVo = new EmployeeVo();
            employeeVo.setOrgId(Long.valueOf(loginDeptAuth()));
            List<EmployeeVo> employees = employeeService.peopleJobList(employeeVo);
            Map<String, Long> creatorMap = employees.stream().collect(Collectors.toMap(EmployeeVo::getNickName, EmployeeVo::getId));

            // 年级
            QueryWrapper<StudentClassGrade> wrapper = new QueryWrapper<>();
            wrapper.eq("deleted", 0);
            List<StudentClassGrade> gradelist = classGradeService.list(wrapper);
            Map<String, Long> gradeMap = gradelist.stream().collect(Collectors.toMap(StudentClassGrade::getName, StudentClassGrade::getId));

            // 查询cof_id
            QueryWrapper<TRenewalAlertsConfig> alertQw = new QueryWrapper<>();
            alertQw.eq("org_Id",loginDeptAuth());
            alertQw.eq("is_delete",0);
            TRenewalAlertsConfig  renewalAlerts = renewalAlertsConfigService.getOne(alertQw);
            for (StudentClueDto dto : easyPoisList) {
                if (dto == null) {
                    continue;
                }
                if (StrUtil.isEmpty(dto.getName()) || StrUtil.isEmpty(dto.getMobile())) {
                    continue;
                }
                //判断手机号是否填写正确
                boolean isPhoneNumber = ReUtil.isMatch("^1[3-9]\\d{9}$", dto.getMobile());
                if(!isPhoneNumber){
                    continue;
                }
                QueryWrapper<StudentUser> wrapperSu = new QueryWrapper<>();
                QueryWrapper<Student> wrapper1 = new QueryWrapper<>();
                wrapperSu.eq("mobile", dto.getMobile());
                StudentUser one = studentUserService.getOne(wrapperSu);
                wrapper1.eq("name", dto.getName());
                wrapper1.eq("org_id", Long.parseLong(loginDeptAuth()));
                wrapper1.eq("deleted", 0);
                Student one1 = studentService.getOne(wrapper1);

                if (one != null && one1 != null) {
                    // 电话号重复
                    continue;
                }

                Student student = new Student();
                BeanUtils.copyProperties(dto, student);
                student.setAttendSchool(dto.getSchoolName());
                student.setStage(stage);
                student.setOrgId(Long.parseLong(loginDeptAuth()));
                student.setFamilyRel("无");
                student.setCofId(Math.toIntExact(renewalAlerts.getId()));
                if (dto.getAddTime() == null){
                    student.setAddTime(LocalDateTime.now());
                } else {
                    student.setAddTime(dto.getAddTime());
                }
                // 出生日期
                if (dto.getBirthday() == null){
                    student.setBirthday(null);
                } else {
                    student.setBirthday(dto.getBirthday());
                }

                // 创建人
                if (dto.getCreatName() == null) {
                    student.setCreator(getUserId());
                } else if (creatorMap.containsKey(dto.getCreatName())) {
                    student.setCreator(creatorMap.get(dto.getCreatName()));
                } else {
                    student.setCreator(getUserId());
                }
                // 来源
                String joinWay = dto.getJoinWay();
                if (joinWay == null) {
                    student.setJoinWay(null);
                } else if (sourceMap.containsKey(joinWay)) {
                    student.setJoinWay(sourceMap.get(joinWay));
                } else {
                    student.setJoinWay(null);
                }

                // 添加年级
                if (dto.getGradeName() == null) {
                    student.setGradeId(null);
                } else if (gradeMap.containsKey(dto.getGradeName())) {
                    student.setGradeId(gradeMap.get(dto.getGradeName()));
                } else {
                    student.setGradeId(null);
                }


                // 添加家长手机号
                StudentUser defaultUser = new StudentUser();
                defaultUser.setMobile(dto.getMobile());
                defaultUser.setName(null);
                defaultUser = studentUserService.existOrCreate(defaultUser);

                student.setUserId(defaultUser.getId());
                list.add(student);

                // 添加学生家长关联表
                StudentContactsUser user = new StudentContactsUser();
                user.setUserId(student.getUserId());
                user.setStudentId(student.getId());
                studentContactsUserService.save(user);
            }

            boolean b = studentService.saveBatch(list);
            return b ?
                    AjaxResult.success("成功导入" + list.size() + "条记录") :
                    AjaxResult.error("姓名和手机号重复");
        } catch (
                Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    @PostMapping("importEnroll")
    @ApiOperation(value = "导入数据")
    public AjaxResult importEnroll(@RequestBody MultipartFile file, Integer stage) {
        //导入
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(0);
        try {
            // 解析excel获取对应list
            List<EnrollmentStuDto> easyPoisList = ExcelImportUtil.importExcel(file.getInputStream(), EnrollmentStuDto.class, params);
            List<StudentCourse> list = new ArrayList<>();
            List<Student> list1 = new ArrayList<>();
            for (EnrollmentStuDto dto : easyPoisList) {
                // 名字必须不为空所以这里校验名字不为空
                if (StrUtil.isEmpty(dto.getName())) {
                    continue;
                }
                if (StrUtil.isNotEmpty(dto.getName())) {
                    QueryWrapper<StudentUser> wrapper = new QueryWrapper<>();
                    QueryWrapper<Student> wrapper1 = new QueryWrapper<>();
                    wrapper.eq("mobile", dto.getMobile());
                    StudentUser one = studentUserService.getOne(wrapper);
                    wrapper1.eq("name", dto.getName());
                    wrapper1.eq("deleted", 0);
                    Student one1 = studentService.getOne(wrapper1);
                    if (one != null) {
                        // 电话号重复
                        return AjaxResult.success("电话号重复");
                    }
                    if (one1 != null) {
                        // 姓名重复
                        return AjaxResult.success("姓名重复");
                    }
                    Student student = new Student();
                    // 跟进人
                    EmployeeVo e = employeeService.selectEmp(dto.getCounselor());
                    EmployeeVo m = employeeService.selectMmp(dto.getManagement());
                    if (e == null) {
                        // 跟进人
                        student.setCounselorId(null);
                    } else {

                        student.setCounselorId(e.getUserId());
                    }
                    if (m == null) {

                        student.setManagementId(null);
                    } else {
                        // 学管师
                        student.setManagementId(m.getUserId());
                    }

                    student.setStage(stage);
                    student.setOrgId(Long.parseLong(loginDeptAuth()));
                    if (dto == null) {
                        continue;
                    }
                    // 名字必须不为空所以这里校验名字不为空
                    StudentCourse studentCourse = new StudentCourse();
                    // copy实体类
                    BeanUtils.copyProperties(dto, studentCourse);
                    studentCourse.setOrgId(Long.parseLong(loginDeptAuth()));


                    if (dto.getCourseName().equals("null")) {
                        studentCourse.setCourseId(0L);
                    }
                    // 查询课程
                    QueryWrapper<TCourse> wr = new QueryWrapper<>();
                    wr.eq("name", dto.getCourseName());
                    TCourse one2 = tCourseService.getOne(wr);
                    if (one2 == null) {
                        studentCourse.setCourseId(0L);
                    }


                    // 查询班级
                    QueryWrapper<StudentClass> sClass = new QueryWrapper<>();
                    sClass.eq("name", dto.getClassName());
                    StudentClass cla = classService.getOne(sClass);
                    TStudentClassRela tStudentClassRela = new TStudentClassRela();
                    if (cla == null) {
                        tStudentClassRela.setClassId(0L);
                    } else {
                        tStudentClassRela.setClassId(cla.getId());
                    }

                    // 查询定价
                    QueryWrapper<TCoursePrice> price = new QueryWrapper<>();
                    price.eq("name", dto.getPriceName());
                    TCoursePrice pri = tCoursePriceService.getOne(price);
                    if (pri == null) {
                        continue;
                    } else {
                        studentCourse.setPriceId(Integer.parseInt(pri.getId().toString()));
                        studentCourse.setCourseAmount(pri.getTotalPrice());
                        studentCourse.setDiscountAmount(pri.getDiscountedPrice());
                        studentCourse.setOriginalUnitPrice(pri.getOriginalUnitPrice());
                        studentCourse.setUnitPrice(pri.getUnitPrice());
                    }
                    studentCourse.setType(1);
                    studentCourse.setStartDate(LocalDate.now());
                    studentCourse.setState(1);
                    studentCourse.setDeleted(0);
                    studentCourse.setAddTime(LocalDateTime.now());
                    LocalDateTime localDateTime = DateUtils.getLocalDateTime(studentCourse.getStartDate() + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                    String courseOrderNo = tCourseOrderTask.getOrderNo1(localDateTime, "courseOrderNo", studentCourse.getCourseId());
                    studentCourse.setOrderNo(courseOrderNo);

                    EmployeeVo c = employeeService.selectMmp(dto.getCreatorName());
                    if (c == null) {
                        studentCourse.setCreator(getUserId());
                    }
                    studentCourse.setCreator(c.getId());

                    student.setUserId(getUserId());
                    student.setStage(stage);
                    student.setOrgId(Long.parseLong(loginDeptAuth()));
                    student.setName(dto.getName());
                    student.setMobile(dto.getMobile());
                    String gender = dto.getGender();
                    if (gender.equals("null")) {
                        student.setGender(2);
                    }
                    if (gender.equals("男")) {
                        student.setGender(0);
                    } else if (gender.equals("女")) {
                        student.setGender(1);
                    }
                    dto.setOrgId(Long.parseLong(loginDeptAuth()));

                    studentService.save(student);
                    studentCourse.setStudentId(student.getId());
                    tStudentClassRela.setStudentId(student.getId());
                    tStudentClassRela.setDeleted(0);
                    tStudentClassRela.setCreator(getUserId());//创建人
                    tStudentClassRela.setAddTime(LocalDateTime.now());

                    tStudentClassRela.setOrgId(Long.parseLong(loginDeptAuth()));

                    BeanUtils.copyProperties(dto, student);
                    studentCourse.setCourseId(one2.getId());//course_id课程id
                    studentCourseService.save(studentCourse);
                    tStudentClassRela.setConsumeCourseId(studentCourse.getCourseId());//默认消费课程
                    studentClassRelaService.save(tStudentClassRela);
//                    list.add(studentCourse);
//                    list1.add(student);
                }
            }
//            boolean b = studentCourseService.saveBatch(list);
//            System.out.println("++++++++++++"+b);
            return AjaxResult.success("成功导入" + easyPoisList.size() + "条记录");

        } catch (Exception e) {
            System.out.println(e.getMessage());
//            return  AjaxResult.error("导入出错");
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出 在读/线索
     *
     * @param
     * @param response
     */

    @RequestMapping("/export")
    public void export(@RequestBody Student student, HttpServletResponse response) {
        student.setSize(999999999l);
        student.setCurrent(1l);
        //1.查询数据
        // 2在读 5历史
        student.setOrgId(Long.parseLong(loginDeptAuth()));
        student.setDeleted(0);
        List<Student> list = studentService.getList(student);
        List<StudentClueExportDto> studentClueDtos = JSON.parseArray(JSON.toJSONString(list), StudentClueExportDto.class);
        // 男 0 女1

        if (studentClueDtos.size() == 0) {
            return;
        }
        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "学员导出");
        //参数1：表格参数  参数2：实体类  参数3：数据
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, StudentClueDto.class, studentClueDtos);
        //3.返回表格
        //设置表格文件名字
        String fileName = "学员导出";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/enrollExport")
    public void enrollExport(@RequestBody EnrollmentStuDto student, HttpServletResponse response) {
        //1.查询数据
        // 2在读 5历史
        long orgId = Long.parseLong(loginDeptAuth());
        student.setOrgId(orgId);
        student.setCreator(getUserId());
        List<EnrollmentStuDto> list = studentService.enrollmentList(student);
        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "报读情况导出");
        //参数1：表格参数  参数2：实体类  参数3：数据
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, EnrollmentStuDto.class, list);
        //3.返回表格
        //设置表格文件名字
        String fileName = "报读情况导出";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 成长档案
     *
     * @param student
     * @return
     */
//    @PostMapping("/growthPortfolio")
//    public AjaxResult growthPortfolio(@RequestBody Student student) {
//        List<StudentAdvertisement> list = studentAdvertismentService.getAll(student);
//        return list;
//    }
//

}

